var page_index_artical = 0,
    page_index_video = 0,
    page_index_img = 0,
    contentTypeAticle = 'Article',
    contentTypeVideo = 'Video',
    contentTypeImg = 'Image',
    href = window.siteURL + "comment/list/index.shtml?contentID=",
    cur_sortType,
    cur_attributes,
    catalogid = '',
    pageSize = 10;

(function($){
//==== start 资源路径查找 ====
  var getCurrentScript = function (base) {
  	if (document.currentScript) {
  		return document.currentScript.src; //FF,Chrome
  	};
  	var stack;
  	try {
  		a.b.c(); //强制报错,以便捕获e.stack
  	} catch (e) { //safari的错误对象只有line,sourceId,sourceURL
  		stack = e.stack;
  		if (!stack && window.opera) {
  			//opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取
  			stack = (String(e).match(/of linked script \S+/g) || []).join(" ");
  		}
  	}
  	if (stack) {
  		stack = stack.split(/[@ ]/g).pop(); //取得最后一行,最后一个空格或@之后的部分
  		stack = stack[0] === "(" ? stack.slice(1, -1) : stack.replace(/\s/, ""); //去掉换行符
  		return stack.replace(/(:\d+)?:\d+$/i, ""); //去掉行号与或许存在的出错字符起始位置
  	}
  	var nodes = (base ? document : head).getElementsByTagName("script"); //只在head标签中寻找
  	for (var i = nodes.length, node; node = nodes[--i]; ) {
  		if (node.readyState === "interactive") {
  			return node.src;
  		}
  	}
  	var node=nodes[nodes.length - 1];
  	return node.hasAttribute ? node.src : node.getAttribute("src", 4);
  }

  var jspath = getCurrentScript(true);
  var scripts = document.getElementsByTagName('script'),
  script = document.currentScript || scripts[scripts.length - 1];

  JSLIBPATH = jspath.substr(0, jspath.lastIndexOf('/') + 1);

//==== end 资源路径查找 ====

  $(function(){
    var previewSiteLink = window.frontAppContext + 'ui/preview/site/'+window.siteID;
    $('#siteLink').attr('href', window.isPreview? previewSiteLink:window.siteURL);//面包屑路径
    if(window.isPreview){
      $('#home>a').attr('href', previewSiteLink);//头部
    }

    var menuBtnImg = $('.head .menu-btn img');

    //==== start 导航菜单 ====
	   $('.menu-btn').on('click', function(e){
       e.stopPropagation();
       // 隐藏搜索框
       $('.search input').hide();
       $('.others .input').removeClass('min');
       // 切换导航显示状态
       if($('.head .menu').css('display') == 'none') {
         $('.head .menu').css({top: $('.head').height() + 20});
         $('.head .menu').slideDown();
         $(this).find('img').attr("src",JSLIBPATH+ "../images/menu_a.png");
         $(this).find('img').addClass('active');
       }else {
         $('.head .menu').slideUp();
         $(this).find('img').attr("src",JSLIBPATH+ "../images/menu.png");
         $(this).find('img').removeClass('active');
       }
     })
     //窗口变动时，重置导航显示状态
     $(window).resize(function(){
       if($(document.body).width() < 992){
         $('.head .menu').hide();
         $('.head .menu').css({top: $('.head').height()});
         menuBtnImg.attr("src",JSLIBPATH+ "../images/menu.png");
         menuBtnImg.removeClass('active');
       }else {
        $('.head .menu').show();
        $('.head .menu').css({top: ''});
       }
     })

     //==== end 导航菜单 ====

     //==== start 点击搜索 ====

     $('.head .search a').on('click', function(e){
       e.stopPropagation();
      // 置空输入框内容
      $('.head .search input').val('');
      $(this).attr('href','JavaScript:;');
      searchInp();

      if(window.innerWidth >= 992){
          //去掉多余样式
          $('.head .others .input').css({top: ''});
          $('.head .others .input').removeClass('min');
          // 切换搜索框显示状态
          if ($('.head .others input').css('display') == 'none') {
            $('.head .search input').show();
            $('.head input').animate({width: 250,'padding-left': 5,'padding-right': 5,'border-width': 1,opacity: 1}, 300);
          }else {
            $('.head .search input').hide();
            $('.head input').animate({width: 0,'padding-left': 0,'padding-right': 0, 'border-width': 0,opacity: 0}, 300);
          }
      }else {
        // 切换搜索框显示状态
        if ($('.head .others input').css('display') == 'none') {
          $('.head .search input').show();
          $('.head .others .input').addClass('min');
          $('.head input').css({width: '100%'});
          $('.head .others .input.min').css({top: $('.head').height()});
          // 隐藏导航
          $('.head .head .menu').slideUp();
          $('.head .menu-btn img').attr("src",JSLIBPATH+ "../images/menu.png");
          $('.head .menu-btn img').removeClass('active');
        }else {
          $('.head .search input').hide();
          $('.head .others .input').removeClass('min');
        }
      }
    });

    searchInp();

    function searchInp() {
      if(window.innerWidth >= 992){
        $('.others .input').css({right: $('.others ul').width() - 10});
      }else {
        $('.others .input').css({right: -61});
      }
    }
    $('.head .search input').on('click', function(e){
      e.stopPropagation();
    });

    // 窗口变动时，重置输入框显示状态
    $(window).resize(function(){
      $('.head .search input').hide();
      $('.head .others .input').removeClass('min');
      searchInp();
    })

    //==== end 点击搜索 ====

    //==== start 点击隐藏导航和搜索框 ====
    $(document).on('click', function(e){
      e.stopPropagation();
      $('.head .search input').hide();
      $('.head .others .input').removeClass('min');
      if(window.innerWidth < 768){
        $('.head .head .menu').slideUp();
        $('.head .menu-btn').find('img').attr("src",JSLIBPATH+ "../images/menu.png");
        $('.head .menu-btn').find('img').removeClass('active');
      }
    })

    //==== end 点击隐藏导航和搜索框 ====


    //==== start 新闻列表 卡片与列表展示切换 ====
    var el_list = $('.switch a.switch-list');
    var el_panel = $('.switch a.switch-panel');
    // 卡片式
    var switch_panel = function(){
      el_panel.addClass('active');
      el_panel.find('img').attr("src",JSLIBPATH+ "../images/icon_11_a.png");
      el_list.find('img').attr("src",JSLIBPATH+ "../images/icon_12.png");
      el_list.removeClass('active');
      $('.news-recommend .news-item').addClass('col-sm-6 col-md-6');
      $('.news-recommend .news-item .box').removeClass('col-sm-4 col-md-4');
      $('.news-recommend .news-item .right').removeClass('col-xs-12 col-sm-8 col-md-8');
      $('.news-recommend .news-item').css({'padding-left': 15, 'padding-right': 15, 'border-bottom': 'none'});
      $('.news-recommend .news-item .box').css({ float: 'none'})
      $('.news-recommend .news-item .right h2').css({'margin-top': 10, 'margin-bottom':10})
    }
    // 列表式
    var switch_list = function (){
      el_list.addClass('active');
      el_list.find('img').attr("src",JSLIBPATH+ "../images/icon_12_a.png");
      el_panel.find('img').attr("src",JSLIBPATH+ "../images/icon_11.png");
      el_panel.removeClass('active');
      $('.news-recommend .news-item').removeClass('col-sm-6 col-md-6');
      $('.news-recommend .news-item .box').addClass('col-sm-4 col-md-4');
      $('.news-recommend .news-item .right').addClass('col-xs-12 col-sm-8 col-md-8');
      $('.news-recommend .news-item').css({'padding-left': 0, 'padding-right': 0, 'border-bottom': '1px dashed #ddd'});
      if($(document).width() > 768){
        $('.news-recommend .news-item .box').css({ float: 'left'})
        $('.news-recommend .news-item .right h2').css({'margin-top': 0, 'margin-bottom':0})
      }
    }
    // 点击切换
    el_panel.on('click', switch_panel);
    el_list.on('click', switch_list);
    // 窗口变动时，重置输卡片列表展示状态
    $(window).resize(function(){
      if(el_list.hasClass('active')){
        if($(document).width() > 768){
          $('.news-recommend .news-item .box').css({ float: 'left'})
        }else {
          $('.news-recommend .news-item .box').css({ float: 'none'})
        }
      }
    });

    //==== end 新闻列表 卡片与列表展示切换 ====

    //==== start 回到顶部 ====
    $('.go_top').click(function() {
      $('html,body').animate({scrollTop:0}, 500);
      return false;
    });
    var height=$(window).height();
    var scrollHandler = function(evt){
      var top = Math.max(document.documentElement.scrollTop, document.body.scrollTop)
      if (top>height){
          $(".go_top").fadeIn(500);
      }else{
          $(".go_top").fadeOut(500);
      }
    }
    $(document.body).on('scroll', scrollHandler);
    $(window).on('scroll', scrollHandler);

    //==== end 回到顶部 ====

    //==== start 去掉浮动 ====
    $('.news-list .news-item:nth-child(odd)').css({clear: 'left'});
    $('.detail-page .img-list-box:nth-child(odd)').css({clear: 'left', 'padding-left': 0});
    $('.detail-page .img-list-box:nth-child(even)').css({'padding-right': 0});

    //==== end 去掉浮动 ====

    //==== start 列表页加载更多&评论数 ====

    //列表小于10条隐藏加载更多按钮
    if($('.articles-item-box .news-item').length < 10){
      $('.articles-item-box .more').hide();
    }
    if($('.videos-item-box .news-item').length < 10){
      $('.videos-item-box .more').hide();
    }
    if($('.images-item-box .news-item').length < 10){
      $('.images-item-box .more').hide();
    }

    //获取评论数id
    var ids = [];

    $('span.total-commend').each(function(){
      var id = $(this).attr('id');
			if ($.isNumeric(id)) {
				ids.push(id);
			}
    })
		if(ids.length > 0) {
			commentTotal(ids);
		}
    $("#mylist").bind('onRecommendLoaded',function(e,ids){
      $("#mylist").removeClass('hide');
      commentTotal(ids);

      //没有图片处理
      $('#mylist .news-item').each(function(){
        if($(this).find('.box img').attr('src') == 'null' || $(this).find('.box img').attr('src') == ''){
          $(this).find('.box').hide();
          $(this).find('.right').removeClass('col-xs-12 col-sm-8 col-md-8');
        }
      });

      if(ids == ''){
        $('.news-recommend .more-btn').text('没有更多内容了');
        $('.news-recommend .more-btn').off('click');
      }

      if($(".switch-panel.active").length){
        $(".switch-panel.active").click()
      }
    })

    //首页推荐
    // $('.news-recommend .more-btn').on('click',function(e){
    //   window._zcms_recommend.getNext();
    // })

     // //点击加载更多按钮，加载10条数据
     // $('.more-btn').on('click',function(e){
     //   // 文章列表
     //    if($('.articles-item-box').css('display') == 'block'){
     //      page_index_artical ++;
     //      cur_sortType = 'OrderFlag';
     //      cur_attributes = 'Recommend';
     //      if($('.list-page').length){
     //        cur_attributes = '';
     //      }
     //      loadMore(page_index_artical,contentTypeAticle, cur_sortType, cur_attributes, catalogid);
     //    }
     //   // 视频列表
     //   if($('.videos-item-box').css('display') == 'block'){
     //     page_index_video ++;
     //     cur_sortType = 'OrderFlag';
     //     cur_attributes = '';
     //     loadMore(page_index_video,contentTypeVideo, cur_sortType, cur_attributes, catalogid);
     //   }
     //   // 图片列表
     //   if($('.images-item-box').css('display') == 'block'){
     //     page_index_img ++;
     //     cur_sortType = 'OrderFlag';
     //     cur_attributes = '';
     //     loadMore(page_index_img,contentTypeImg, cur_sortType, cur_attributes, catalogid);
     //   }
     //
     // })

    //==== end 列表页加载更多&评论数 ====

    //==== start 详细页换一批 ====

    window.refresh_index = 0;
    $('.refresh').on('click',function(){
      window.refresh_index ++;
      cur_attributes = 'Recommend';
      contentType = 'Article';
      var conids = [];

      $('.recomment-news .con-box').each(function(){
        var re_id = $(this).attr('id');
        conids.push(re_id);
      })
      refresh(contentType, cur_attributes, conids.join(','),2);
    })

    //==== end 详细页换一批 ====

  })

  })(window.jQuery);

  // 加载更多
  function loadMore(index,type, sortType, attributes, catalogid){
    $.ajax({
      url : window.frontAppContext + 'front/contents?siteID='+ siteID +'&pageIndex='+ index +'&isPreview='+ isPreview +'&contentType=' + type + '&sortType='+ sortType +'&attributes='+ attributes + '&catalogID=' + catalogid +'&pageSize=' + pageSize,
      type : "get",
      async: true,
      success : function(result) {
        var json = result.data.data;
        var current_arr = [];

        for(var k in json){
          if(!isNaN(k)){
            current_arr.push(json[k].ID);
            var html_artical = '<div class="news-item clearfloat">' +
                                '<div class="box col-sm-4 col-md-4"><a href="'+ json[k].link +'" title="'+ json[k].title +'" target="_blank"><img class="left" src="'+ json[k].logoFile +'" alt=""></a></div>' +
                                '<div class="right col-xs-12 col-sm-8 col-md-8">' +
                                  '<a href="'+ json[k].link +'" title="'+ json[k].title +'" target="_blank"><h2>'+ json[k].title +'</h2></a>' +
                                  '<p>'+ chartWith(json[k].summary,100,'...') +'</p>' +
                                  '<div class="info-box">' +
                                    '<div class="info">' +
                                      '<span class="origin">'+ json[k].source +'</span>' +
                                      '<span class="date">'+ json[k].publishDate +'</span>' +
                                    '</div>' +
                                    '<div class="operate">' +
                                      '<a target="_blank" href="'+ href + json[k].ID +'" class="reply"><img src="'+ window.siteURL +'images/icon_01.png" alt=""><span class="total-commend" id="'+ json[k].ID +'">0</span></a>' +
                                      '<a target="_blank" href="#" class="share"><img src="' + JSLIBPATH + '../images/icon_02.png" alt="">360</a>' +
                                    '</div>' +
                                  '</div>' +
                                '</div>' +
                              '</div>';

              var html_video = '<div class="col-xs-6 col-sm-6 col-md-6 news-item clearfloat">' +
                                '<a href="'+ json[k].link +'" title="'+ json[k].title +'" target="_blank">' +
                                  '<div class="box"><img class="left" src="'+ json[k].logoFile +'" alt=""></div>' +
                                  '<div class="right">' +
                                     '<h2>'+ json[k].title +'</h2>' +
                                    '<div class="info-box">' +
                                      '<div class="info">' +
                                        '<span class="origin">点击次数：'+ json[k].HitCount +'</span>' +
                                        '<span class="date">'+ json[k].publishDate +'</span>' +
                                      '</div>' +
                                    '</div>' +
                                  '</div>' +
                                '</a>' +
                              '</div>';

              var html_img = '<div class="col-xs-6 col-sm-6 col-md-6 news-item clearfloat">' +
                              '<a href="'+ json[k].link +'" title="'+ json[k].title +'" target="_blank">' +
                                '<div class="box"><img class="left" src="'+ json[k].logoFile +'" alt=""></div>' +
                                '<div class="right">' +
                                  '<h2>'+ json[k].title +'</h2>' +
                                  '<div class="info-box">' +
                                    '<div class="info">' +
                                      '<span class="origin">[组图'+ json[k].Quantity +'张]</span>' +
                                      '<span class="date">'+ json[k].publishDate +'</span>' +
                                    '</div>' +
                                  '</div>' +
                                '</div>' +
                              '</a>' +
                            '</div>';
              if($('.articles-item-box').css('display') == 'block'){
                $(".articles-item-box .box-con").append(html_artical);
                if($(".switch-panel.active").length){
                  $(".switch-panel.active").click()
                }
              }
              if($('.videos-item-box').css('display') == 'block'){
                $(".videos-item-box .box-con").append(html_video);
              }
              if($('.images-item-box').css('display') == 'block'){
                $(".images-item-box .box-con").append(html_img);
              }
           }
         }
         // 没有来源，隐藏
         $('.origin').each(function(){
           if($(this).html() == 'null'){
             $(this).hide();
           }
         });
         //没有图片，隐藏图片显示部分
         $('.news-item').each(function(){
           if($(this).find('.box img').attr('src') == 'null' || $(this).find('.box img').attr('src') == ''){
             $(this).find('.box').hide();
             $(this).find('.right').removeClass('col-xs-12 col-sm-8 col-md-8');
           }
         });
         // 没有数据可加载
         if($('.articles-item-box').css('display') == 'block'){
            if(index == Math.ceil(result.total/pageSize)){
              $('.articles-item-box .more-btn').text('没有更多内容了');
            }
          }
         if($('.images-item-box').css('display') == 'block'){
           if(index == Math.ceil(result.total/pageSize)){
             $('.images-item-box .more-btn').text('没有更多内容了');
           }
         }
         if($('.videos-item-box').css('display') == 'block'){
           if(index == Math.ceil(result.total/pageSize)){
             $('.videos-item-box .more-btn').text('没有更多内容了');
           }
         }

         commentTotal(current_arr);
      }
    });
  }
  // 换一批
  function refresh(type, attributes, contentIds,pageSizeR){

    $.ajax({
      url : window.frontAppContext + 'front/contents?siteID='+ siteID +'&pageIndex='+ window.refresh_index +'&isPreview='+ isPreview +'&contentType=' + type +'&attributes='+ attributes +'&pageSize=' + pageSizeR + '&contentIds=' + contentIds + '&orderBy=rand',
      type : "get",
      async: true,
      success : function(result) {
        var json = result.data;
        if(json.length == 0 || json[0] == undefined ){
        	window.refresh_index = 0;
          return;
        }

        var html = '<div class="col-xs-12 col-sm-6 col-md-6 left con-box" id="'+ json[0].ID +'">' +
                      '<div class="clearfloat">' +
                        '<a href="'+ json[0].link +'" title="'+ json[0].title +'" target="_blank">' +
                          '<h2>'+ json[0].title +'</h2>' +
                          '<p>'+ json[0].summary +'</p>' +
                          '<div class="date">' +
                            '<img src="' + JSLIBPATH + '../images/icon_15.png" alt="">' +
                            '<span>'+ json[0].publishDate +'</span>' +
                          '</div>' +
                        '</a>' +
                      '</div>' +
                    '</div>';
        if(json.length>1){
        	var html2 = '<div class="col-xs-12 col-sm-6 col-md-6 right con-box" id="'+ json[1].ID +'">' +
			            '<div class="clearfloat">' +
			            '<a href="'+ json[1].link +'" title="'+ json[1].title +'" target="_blank">' +
			              '<img class="img" src="'+ json[1].logoFile +'" alt="">' +
			              '<h2>'+ json[1].title +'</h2>' +
			              '<div class="date">' +
			                '<img src="' + JSLIBPATH + '../images/icon_15.png" alt="">' +
			                '<span>'+ json[1].publishDate +'</span>' +
			              '</div>' +
			            '</a>' +
			          '</div>' +
			        '</div>';
        	html += html2;
        }
              $(".reco-news-con").html(html);
      }
    });
  }

  // 评论数
  function commentTotal(ids) {
    if(ids instanceof Array){
      ids = ids.join(',');
    }
    if(ids === ''){
      return;
    }
    $.ajax({
      url : window.frontAppContext + 'front/contents/' + ids + '/commentcount',
      type : "get",
      success : function(result) {
      	var countlist = result.data;
      	if(countlist && countlist.length>0){
          countlist.forEach(function(contentitem){
            var contentID = contentitem.contentID;
            var commentTotal = contentitem.commentTotal;
            var personTotal = contentitem.personTotal;
            $("#"+contentID).text(commentTotal);
          });
      	}
      }
    });
  }

  function chartWith(source,len,suffix){
    var result = source;
    if(source && source.length>len){
      result = source.substr(0,len);
      result += suffix;
    }
    return result;
  }
